package com.rzico.sbl.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.view.isVisible
import androidx.core.widget.NestedScrollView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.FragmentHomeBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.HomeContent
import com.rzico.sbl.model.ManagerContent
import com.rzico.sbl.model.QRType
import com.rzico.sbl.model.RecordData
import com.rzico.sbl.other.getTodayDate
import com.rzico.sbl.other.reportEnable
import com.rzico.sbl.other.userRole
import com.rzico.sbl.ui.MessageActivity
import com.rzico.sbl.ui.ScanActivity
import com.rzico.sbl.ui.goods.GoodsActivity
import com.rzico.sbl.ui.manager.BarrelHandleActivity
import com.rzico.sbl.ui.manager.MasterActivity
import com.rzico.sbl.ui.manager.MasterBarrelActivity
import com.rzico.sbl.ui.manager.PickupActivity
import com.rzico.sbl.ui.manager.PickupOrderActivity
import com.rzico.sbl.ui.manual.ManualActivity
import com.rzico.sbl.ui.manual.ManualCallActivity
import com.rzico.sbl.ui.member.MemberActivity
import com.rzico.sbl.ui.order.DeliverActivity
import com.rzico.sbl.ui.order.OrderActivity
import com.rzico.sbl.ui.report.ReportActivity
import com.rzico.sbl.ui.statistic.GoodsRecordActivity
import com.rzico.sbl.ui.statistic.GoodsStatisticActivity
import com.rzico.sbl.ui.statistic.SendActivity
import com.rzico.sbl.ui.statistic.ShareActivity
import com.rzico.sbl.ui.statistic.StockActivity
import com.xinnuo.common.decoration.GridVerticalDecoration
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionElse
import com.xinnuo.common.extend.conditionIf
import com.xinnuo.common.extend.formatDecimal
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.notEmpty
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.orEmpty
import com.xinnuo.common.extend.startActivityEx
import com.xinnuo.common.extend.visible
import com.xinnuo.common.helper.dp2px
import com.xinnuo.common.helper.getString
import com.xinnuo.common.view.FullyGridLayoutManager
import com.xinnuo.common.view.FullyLinearLayoutManager
import com.xinnuo.common_ui.base.NavigationFragment
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.refresh
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.subscribeByFinally
import com.xinnuo.common_ui.view.BadgeTextView
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch


class HomeFragment : NavigationFragment() {

    private var mBinding: FragmentHomeBinding? = null
    private lateinit var mIconAdapter: SlimAdapter

    private val mCallList = arrayListOf<RecordData>()
    private var mCallScrollHeight = 0

    override fun getViewModel() = get<HomeViewModel>()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = FragmentHomeBinding
        .inflate(inflater, container, false)
        .also { mBinding = it }
        .root

    override fun initTitle() {
        initLayout()
        initListener()

        observeData()

        mBinding
            ?.swipeRefresh
            ?.isRefreshing = true

        getData()
    }

    private fun initLayout() {
        mBinding?.let { binding ->
            binding.swipeRefresh.refresh {
                getData()     //刷新销量
                getHomeData() //刷新首页数据
            }

            binding.homeIcons.apply {
                itemAnimator = null
                isNestedScrollingEnabled = false

                layoutManager = FullyGridLayoutManager(getIContext(), 4)

                addItemDecoration(GridVerticalDecoration(vertical = 15f))

                mIconAdapter = SlimAdapter.creator()
                    .register<ManagerContent>(R.layout.item_home_icon) { jector, bean, _ ->

                        // 解构声明
                        val (title, imageId, _, _, count) = bean

                        jector.apply {
                            text(R.id.item_icon_title, title)
                            image(R.id.item_icon_img, imageId)

                            getView<BadgeTextView>(R.id.item_icon_num)
                                .setBadgeCount(count)

                            clicked {
                                when (title) {
                                    "报货" ->
                                        when (getString("roleName")) {
                                            "店主" -> startActivityEx<ReportActivity>()
                                            else -> showToast("只有店主才能报货")
                                        }

                                    "会员" -> startActivityEx<MemberActivity>()
                                    "商品" -> startActivityEx<GoodsActivity>()
                                    "报单" -> startActivityEx<ManualActivity>()
                                    "送货" -> startActivityEx<SendActivity>()
                                    "员工" -> startActivityEx<MasterActivity>()
                                    "推广" -> startActivityEx<ShareActivity>()
                                    "退桶" ->
                                        (userRole in "1,2")
                                            .conditionElse(
                                                actionTrue = {
                                                    startActivityEx<MasterBarrelActivity>()
                                                },
                                                actionFalse = {
                                                    startActivityEx<MasterBarrelActivity>("index" to 2)
                                                }
                                            )

                                    "自提点" -> startActivityEx<PickupActivity>()
                                    "订单" -> startActivityEx<PickupOrderActivity>()
                                    "押桶" -> startActivityEx<BarrelHandleActivity>()
                                    "库存" -> startActivityEx<StockActivity>()
                                }
                            }
                        }
                    }
                    .attachTo(this)
            }

            binding.homeCalls.apply {
                isNestedScrollingEnabled = true
                layoutManager = LinearLayoutManager(getIContext())

                addItemDecoration(SpaceTBDecoration())

                adapter = AutoPollAdapter(mCallList)
            }

            binding.recycleList.apply {
                isNestedScrollingEnabled = false
                layoutManager = FullyLinearLayoutManager(getIContext())

                addItemDecoration(SpaceTBDecoration(bottom = 15f, hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<HomeContent>(R.layout.item_home_list) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_home_name, bean.name)
                            text(R.id.item_home_type, bean.subTitle)
                            text(R.id.item_home_price, "${bean.price.formatDecimal()} 元")
                            text(R.id.item_home_num, bean.quantity)

                            with<ImageView>(R.id.item_home_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            with<ImageView>(R.id.item_home_rank) {
                                when (index) {
                                    0 -> it.apply { visible() }
                                        .setImageResource(R.mipmap.icon_home13)

                                    1 -> it.apply { visible() }
                                        .setImageResource(R.mipmap.icon_home14)

                                    2 -> it.apply { visible() }
                                        .setImageResource(R.mipmap.icon_home15)

                                    else -> it.gone()
                                }
                            }

                            clicked {
                                startActivityEx<GoodsRecordActivity>(
                                    "productId" to bean.productId.orEmpty(),
                                    "dateMode" to "1",
                                    "beginDate" to getTodayDate(),
                                    "endDate" to getTodayDate()
                                )
                            }
                        }
                    }
                    .attachTo(this)
            }
        }
    }

    /**
     * 设置点击事件
     */
    private fun initListener() {
        mBinding?.apply {
            // 滑动监听
            homeScroll.setOnScrollChangeListener(
                NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
                    // 变化高度范围，单位像素
                    val changeHeight = dp2px(102f)

                    // 当滑动距离 <= 指定高度的时候，改变背景的透明度，达到渐变的效果
                    (scrollY in 0..changeHeight)
                        .conditionElse(
                            actionTrue = {
                                // 计算透明度值
                                val alpha = scrollY.toFloat() / changeHeight
                                // 改变图片背景的透明度
                                homeImg.alpha = 1f - alpha
                                // 改变标题背景的透明度
                                homeBg.alpha = alpha
                            },
                            actionFalse = {
                                // 将图片背景设置为非透明状态
                                homeImg.alpha = 0f
                                // 将标题背景设置为透明状态
                                homeBg.alpha = 1f
                            }
                        )
                }
            )

            // 扫一扫
            layout
                .homeScan
                .oneClick {
                    startActivityEx<ScanActivity>(
                        "mode" to QRType.HOME,
                        "from" to "home"
                    )
                }

            // 消息
            layout
                .homeMsg
                .oneClick { startActivityEx<MessageActivity>() }

            // 订单
            homeOrderAll.oneClick { startActivityEx<OrderActivity>() }
            homePay.oneClick { startActivityEx<OrderActivity>("index" to 1) }
            homeWait.oneClick { startActivityEx<OrderActivity>("index" to 2) }
            homeSend.oneClick { startActivityEx<OrderActivity>("index" to 3) }
            homeBack.oneClick { startActivityEx<OrderActivity>("index" to 4) }

            // 运单
            homeWayAll.oneClick { startActivityEx<DeliverActivity>() }
            homeConfirm.oneClick { startActivityEx<DeliverActivity>("index" to 1) }
            homePei.oneClick { startActivityEx<DeliverActivity>("index" to 3) }
            homeDone.oneClick { startActivityEx<DeliverActivity>("index" to 4) }
            homeEnd.oneClick { startActivityEx<DeliverActivity>("index" to 5) }

            // 推广
            homeShareMore.oneClick { startActivityEx<ShareActivity>() }

            // 电话弹单
            homeCallAll.oneClick { startActivityEx<ManualCallActivity>() }

            // 商品统计
            homeSaleAll.oneClick { startActivityEx<GoodsStatisticActivity>() }
        }
    }

    /**
     * livedata 数据监听
     */
    private fun observeData() {
        mBinding?.apply {
            // 公告
            getViewModel()
                .mNotice
                .observe(getLifecycleOwner()) { value ->
                    layout.homeNotice.text = value
                }

            // 消息提示
            getViewModel()
                .mMessageEvent
                .observe(getLifecycleOwner()) { value ->
                    layout.homeMsgHint.isVisible = value > 0
                }

            // 订单数量
            getViewModel()
                .mOrderCount
                .observe(getLifecycleOwner()) {
                    homePayHint.setBadgeCount(it[0])
                    homeWaitHint.setBadgeCount(it[1])
                    homeSendHint.setBadgeCount(it[2])
                    homeBackHint.setBadgeCount(it[3])
                }

            // 运单数量
            getViewModel()
                .mDeliverCount
                .observe(getLifecycleOwner()) {
                    homeConfirmHint.setBadgeCount(it[0])
                    homePeiHint.setBadgeCount(it[1])
                    homeDoneHint.setBadgeCount(it[2])
                    homeEndHint.setBadgeCount(it[3])
                }

            // 退桶单数量
            getViewModel()
                .mBarrelCount
                .observe(getLifecycleOwner()) { arr ->
                    val items = mIconAdapter.getDataList()
                    val index = items.indexOfFirst {
                        it is ManagerContent && it.title == "退桶"
                    }

                    (index > -1)
                        .condition {
                            when (userRole) {
                                in "1,2" ->
                                    (items[index] as ManagerContent).count = arr[0] + arr[1]

                                in "3,10" ->
                                    (items[index] as ManagerContent).count = arr[1]
                            }
                            mIconAdapter.notifyItemChanged(index)
                        }
                }

            // 1管理员、2店长、10客服、3送水工、4推广员、13自提点、14自提店主
            homeOrder.isVisible = userRole in "1,2,10"
            homeWay.isVisible = userRole in "1,2,3,10"
            homeShare.isVisible = userRole in "4"
            homeSaleAll.isVisible =
                userRole != "4" && userRole in "1,2,14"

            // 快捷入口图标
            mIconAdapter.setDataList(
                when (userRole) {
                    "1", "2" ->
                        conditionIf(
                            reportEnable,
                            getViewModel().masterIcons(),
                            getViewModel().masterIconsNoReport()
                        )

                    "3" -> getViewModel().sendIcons()
                    "4" -> getViewModel().shareIcons()
                    "10" -> getViewModel().serveIcons()
                    "13" -> getViewModel().pickIcons()
                    "14" -> getViewModel().pickMasterIcons()
                    else -> emptyList()
                }
            )
        }

        observe<String>("phone_report") { getCallList() }
    }

    /**
     * 首页数据获取
     */
    private fun getHomeData() {
        // 电话接单判断
        mBinding?.let {
            it.homeCall.isVisible =
                userRole in "1,2" && getString("incomeStatus") == "1"

            it.homeCall
                .isVisible
                .condition { getCallList() }
        }

        getViewModel().getNotice()    //刷新公告
        getViewModel().messageCount() //刷新消息

        when (userRole) {
            // 店主、管理员、客服
            "1", "2", "10" -> {
                getViewModel().getListCount(BaseUrl.orderCount)   //刷新订单数
                getViewModel().getListCount(BaseUrl.deliverCount) //刷新运单数
                getViewModel().getBarrelCount()                   //刷新退桶单数
            }
            // 送水工
            "3" -> {
                getViewModel().getListCount(BaseUrl.deliverCount) //刷新运单数
                getViewModel().getBarrelCount()                   //刷新退桶单数
            }
            // 推广员
            "4" -> getShareData()
        }
    }

    /**
     * 来电接单列表
     */
    private fun getCallList() {
        getViewModel()
            .callList(
                onSuccess = {
                    mBinding?.apply {
                        homeCallNum.text = it.recordsTotal

                        it.data.notEmpty {
                            mCallList.clear()
                            mCallList.addItems(this)
                        }

                        (homeCalls.adapter as AutoPollAdapter).notifyDataSetChanged()
                        homeCalls.startRoll()
                    }
                }
            )
    }

    /**
     * 首页推广总计
     */
    private fun getShareData() {
        getViewModel()
            .shareList()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    it.notEmpty {
                        mBinding?.apply {
                            homeScount.text = it[0].promoter
                            homeSamount.text = it[0].amount.formatDecimal()
                        }
                    }
                }
            )
    }

    /**
     * 本月销量
     */
    override fun getData(index: Int, isLoading: Boolean) {
        when (userRole) {
            // 店主、管理员
            "1", "2", "14" -> {
                getViewModel()
                    .saleList()
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByFinally(
                        event = getViewModel(),
                        onSuccess = {
                            mList.apply {
                                clear()
                                addItems(it)
                            }

                            mAdapter.setDataList(mList)
                        },
                        onFinally = {
                            mBinding
                                ?.swipeRefresh
                                ?.isRefreshing = false
                        }
                    )
            }
            // 送水工、推广员、客服
            else -> {
                lifecycleScope.launch {
                    delay(1500)

                    mBinding
                        ?.swipeRefresh
                        ?.isRefreshing = false
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        getHomeData()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        mBinding = null
    }

}